package com.wanter.users.service.impl;

import com.wanter.common.utils.ID.IDutils;
import com.wanter.common.utils.user.UserUtils;
import com.wanter.users.entity.User;
import com.wanter.users.mapper.UserMapper;
import com.wanter.users.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * Created by er on 2017/5/15.
 */
@SuppressWarnings("SpringJavaAutowiringInspection")
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    private final Logger logger = Logger.getLogger(this.getClass());

    public User login(String username, String password) {
        User user = null;
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            user = userMapper.login(username, password);
            if(user!=null) {
                if (logger.isInfoEnabled()) {
                    logger.info("用户登录成功" + user);
                    user.setStrGander(UserUtils.getGander(user.getGander()));//设置性别
                }
            }
             else {
                if (logger.isDebugEnabled()) {
                    logger.debug("用户登录失败: 用户名:" + username + "密码:" + password);
                }
            }
        }
        return user;
    }

    public int insertRegister(User user) {
        User result = userMapper.login(user.getUsername(), user.getPassword());
        if (result == null) {
            if (logger.isInfoEnabled()) {
                logger.info("该用户未被注册!可以使用");
            } else {
                if (logger.isInfoEnabled()) {
                    logger.info("该用户已被注册" + user);
                }
                return -1;
            }
        }
        if (!StringUtils.isEmpty(user.getPassword()) && !StringUtils.isEmpty(user.getUsername())) {
            user.setId(IDutils.getUUID());
            userMapper.insertUser(user);
            if (logger.isInfoEnabled()) {
                logger.info("注册用户成功" + user);
            } else {
                if (logger.isInfoEnabled()) {
                    logger.info("用户名或密码为空,注册失败" + user);
                }
            }

        }
        return 1;
    }

    @Override
    public void updatePassword(String username, String password) {
        User user = this.login(username, password);
        userMapper.updatePassWord(username, password, user.getId());
        if(logger.isInfoEnabled()){
            logger.info("用户"+user+"更改密码成功");
        }
    }
}
